package com.suman.bbcticker.receiver;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;

import com.suman.bbcticker.ApplicationStateObjectsHolder;
import com.suman.bbcticker.service.RssReaderService;

public class ConnectivityManagerReceiver extends BroadcastReceiver {

	private static final String TAG = "ConnectivityManagerReceiver";
	private static Boolean currentNetworkState = null;

	@Override
	public void onReceive(Context context, Intent intent) {
		boolean isNetworkDisconnected = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

		if ((currentNetworkState == null || currentNetworkState == false) && !isNetworkDisconnected) {

			HashMap<Integer, Date> alarmTriggermap = new HashMap<Integer, Date>(ApplicationStateObjectsHolder.alarmTriggerTimeMap);

			if (!alarmTriggermap.isEmpty()) {
				// see if current time > entries trigger time
				for (HashMap.Entry<Integer, Date> alarmTriggerEntry : alarmTriggermap.entrySet()) {
					Date entryDate = alarmTriggerEntry.getValue();

					if (Calendar.getInstance().getTime().getTime() > entryDate.getTime()) {
						// Alarm got Missed..Need to trigger again...And removed
						// from hashmap

						Intent newIntent = new Intent(context, RssReaderService.class);
						newIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, alarmTriggerEntry.getKey());
						context.startService(newIntent);

					}

				}
				ApplicationStateObjectsHolder.alarmTriggerTimeMap.clear();

			}

		}
		if (!isNetworkDisconnected) {
			currentNetworkState = true;
		} else {
			currentNetworkState = false;
		}

	}

}
